import React, { useRef, useState, useEffect } from 'react'
import SoundOffSvg from '../../public/soundOff.svg?react'
import SoundOnSvg from '../../public/soundOn.svg?react'
import './index.css' // 需要创建这个CSS文件
import { useGlobalContext } from '@/contexts/GlobalContext'
import { AUDIO_COUNT } from '@/config/env'

const AudioPlayer: React.FC = () => {
  const audioRef = useRef<HTMLAudioElement>(null)
  const { startAudio, setStartAudio } = useGlobalContext()
  const [autoPlay, setAutoPlay] = useState(false)
  const playCountRef = useRef(AUDIO_COUNT)
  useEffect(() => {
    const audio = audioRef.current
    if (!audio) return
    const handleEnded = () => {
      console.log('audio ended')
      playCountRef.current -= 1

      if (playCountRef.current === 0) {
        // 达到最大播放次数，停止循环播放
        playCountRef.current = 3
        setStartAudio(false)
        // setIsLoop(false)
      } else {
        // 未达到最大播放次数且循环模式开启，继续播放
        audio.currentTime = 0
        audio.play()
      }
    }

    audio.addEventListener('ended', handleEnded)

    return () => {
      audio.removeEventListener('ended', handleEnded)
    }
  }, [playCountRef])
  const togglePlay = () => {
    const audio = audioRef.current
    if (!audio) return
    setAutoPlay(!autoPlay)
  }
  function playAudio() {
    const audio = audioRef.current
    if (!audio) return
    audio.play()
  }

  useEffect(() => {
    if (startAudio) {
      playAudio()
    }
  }, [startAudio])

  return (
    <div className="rounded-lg">
      <audio
        ref={audioRef}
        src="/src/public/voiceTip.wav"
        autoPlay={autoPlay}
        loop={false}
        muted={!autoPlay}
      />
      <div onClick={togglePlay} className="cursor-pointer">
        {autoPlay ? (
          <SoundOnSvg
            className={`${startAudio ? 'shake-animation text-red-600' : 'text-[#00ff88]'}`}
            width="24px"
            height="24px"
          />
        ) : (
          <SoundOffSvg className="text-red-600" width="30px" height="30px" />
        )}
      </div>
    </div>
  )
}
export default AudioPlayer
